package service

import (
	"context"
	"go.uber.org/zap"
	v1 "golang-sgg-daijia/api/v1"
	"golang-sgg-daijia/internal/model"
	"golang-sgg-daijia/internal/repository/minio"
	"golang-sgg-daijia/internal/repository/mongodb"
	"golang-sgg-daijia/internal/repository/tencentcloud"
	"mime/multipart"
	"strconv"
)

type MonitorService interface {
	Upload(ctx context.Context, file *multipart.FileHeader, req *v1.OrderMonitorForm) (bool, error)
}

func NewMonitorService(
	service *Service,
	minioClient minio.MinioClient,
	orderMonitorRecordDao mongodb.OrderMonitorRecordDao,
	cosClient tencentcloud.CosClient,
) MonitorService {
	return &monitorService{
		Service:               service,
		minioClient:           minioClient,
		orderMonitorRecordDao: orderMonitorRecordDao,
		cosClient:             cosClient,
	}
}

type monitorService struct {
	*Service
	minioClient           minio.MinioClient
	orderMonitorRecordDao mongodb.OrderMonitorRecordDao
	cosClient             tencentcloud.CosClient
}

func (s *monitorService) Upload(ctx context.Context, file *multipart.FileHeader, req *v1.OrderMonitorForm) (bool, error) {
	f, err := file.Open()
	if err != nil {
		s.logger.WithContext(ctx).Error("fileService|Upload|Open", zap.Error(err))
		return false, err
	}
	//url, err := s.minioClient.PutObject(ctx, file.Filename, f, file.Size)
	//if err != nil {
	//	return false, err
	//}
	err = s.cosClient.Put(ctx, file.Filename, f, nil)
	if err != nil {
		return false, err
	}
	// 增加文本审核
	result, keywords, err := s.cosClient.TextAudit(ctx, req.Content)
	if err != nil {
		return false, err
	}
	orderMonitorRecord := &model.OrderMonitorRecord{
		OrderID: req.OrderID,
		FileURL: file.Filename,
		Content: req.Content,
		Result: strconv.Itoa(result),
		Keywords: keywords,
	}
	_, err = s.orderMonitorRecordDao.InsertOne(ctx, orderMonitorRecord)
	if err != nil {
		return false, err
	}

	return true, nil
}
